package logic

import (
	"os"
	"path"
	"strings"
)

type Process struct {
	*Unit
}

func (container *Process) Analyse(info *UnitInfo) error {
	if info.Command == "" {
		// 命令为空，获取args第一个为命令
		blankIndex := strings.Index(info.Args, " ")
		if blankIndex < 0 {
			info.Command = info.Args
			info.Args = ""
		} else if blankIndex == 0 {
			info.Command = strings.Trim(info.Args, "")
			info.Args = ""
		} else {
			info.Command = info.Args[:blankIndex]
			info.Args = info.Args[blankIndex+1:]
		}
	}

	if strings.HasPrefix(info.Command, "./") {
		// 工作目录下执行命令：添加执行权限
		if err := os.Chmod(path.Join(info.WorkDir, info.Command), 0777); err != nil {
			return err
		}
	}

	return nil
}

func (container *Process) Start() error {
	info := container.Info
	env := make([]string, 0, len(container.Info.Env))
	for key, value := range container.Info.Env {
		env = append(env, key+"="+value)
	}
	log, err := GenerateLog(container.Unit)
	if err != nil {
		return err
	}
	pid, err := StartProcess(log, info.WorkDir, env, info.Command, info.Args)
	if err != nil {
		return err
	}
	container.Pid = pid
	return nil
}

func (container *Process) Find() bool {
	return FindProcess(container.Pid)
}

func (container *Process) Stop() error {
	if FindProcess(container.Pid) {
		if err := StopProcess(container.Pid); err != nil {
			return err
		}
	}
	return nil
}

func (container *Process) Clean() error {
	if !container.Info.IsOrigin || container.Info.IsDownload {
		// 删除工作目录
		_ = os.RemoveAll(container.Info.WorkDir)
	}
	return nil
}

func (container *Process) Watch() map[string]interface{} {
	info, err := ProcessInfo(container.Pid)
	if err != nil {
		info = map[string]interface{}{"cpu": "0%"}
	}
	stat, err := ProcessStat(container.Pid)
	if err != nil {
		stat = map[string]interface{}{}
	}
	if _, ok := stat["mem"]; ok {
		info["mem"] = stat["mem"]
	}
	return info
}
